module(..., package.seeall)

local adSpace

function new(obj)

	local soundOnOff = sound
	local localGroup = display.newGroup()
	local loadingImage
	
	local backgroundSound = audio.loadStream("audios/begin.mp3" )
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function networkListener( event )
		if theTimer then
			timer.cancel(theTimer)
		end
		if waitingGroup then
			for i = waitingGroup.numChildren,1,-1 do
				local child = waitingGroup[i]
				child:removeSelf()
				child = nil
			end  
			waitingGroup:removeSelf()
			waitingGroup = nil
		end
		if (event.isError) then
			--
			native.showAlert( "", "Kết nối máy chủ gặp sự cố, xin vui lòng kiểm tra lại kết nối mạng!", { "OK"}, getAddressServer )
		else
			local result = event.response
			serverhost = result
			
			transition.to(localGroup, {time=500, alpha=0,
				onComplete = function(event) 
					--waiting 0,5 sec
					theTimer = timer.performWithDelay(50, function(event)
						director:changeScene("menu", nil)
					end, 1)
				end
			})
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	function getAddressServer()
		local url = "http://www.azsoft.com.vn/myapp/nauan/server.ashx?action=ADDSVOLPA"
		network.request(url, "GET", networkListener )
	end
	-----------------------------------------------------
	--init screen 
	-----------------------------------------------------
	local drawScreen = function()
		loadingImage = display.newImageRect( "images/bgloading.png", display.contentWidth, display.contentHeight)
		loadingImage.x = display.contentWidth/2
		loadingImage.y = display.contentHeight/2
	
		localGroup:insert(loadingImage)
		timer.performWithDelay(500, getAddressServer, 1)
		
		audio.play( backgroundSound, { channel=1, loops=-1, fadein=5000 }  )
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	drawScreen ()
	-----------------------------------------------------
	--
	-----------------------------------------------------
	unloadMe = function()
		if theTimer then
		   timer.cancel(theTimer)	
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	local function onSystemEvent( event )
		if event.type == "applicationExit" then
			unloadMe()
		end
	end
	-----------------------------------------------------
	--
	-----------------------------------------------------
	Runtime:addEventListener( "system", onSystemEvent )
	return localGroup
end
